<template>
  <div>
    <el-card style="width:100%">
      <div slot="header"
           class="clearfix">
        <span>{{title}}</span>
      </div>
      <el-form ref="productForm"
               :model="productForm"
               :rules="formRule"
               label-position="right"
               label-width="120px">
        <el-form-item label="产品编号"
                      prop="productCode"
                      style="width:30%">
          <!-- <el-input v-model="productCode"
                    placeholder=""
                    :disabled='topDisabled'></el-input> -->

          <el-autocomplete v-model="productCode"
                           :fetch-suggestions="querySearchAsync"
                           placeholder="请输入产品编号"
                           @select="handleSelect"
                           :disabled="topDisabled">
          </el-autocomplete>

        </el-form-item>
        <el-form-item label="产品名称"
                      prop="productStoreName"
                      style="width:30%">
          <el-input v-model="productForm.productStoreName"
                    placeholder="请输入产品名称"
                    :disabled='isDisabled'></el-input>
        </el-form-item>
        <el-form-item label="产品料号"
                      prop="productNumber"
                      style="width:30%;">
          <el-input v-model="productForm.productNumber"
                    placeholder="请产品料号"
                    :disabled='isDisabled'></el-input>
        </el-form-item>
        <el-form-item label="产品售价"
                      prop="price"
                      style="width:30%;">
          <el-input v-model="productForm.price"
                    placeholder="请输入产品售价"
                    :disabled='isDisabled'></el-input>
        </el-form-item>
        <el-form-item label="成本价"
                      prop="costPrice"
                      style="width:30%;">
          <el-input v-model="productForm.costPrice"
                    placeholder="请输入产品售价"
                    :disabled='isDisabled'></el-input>
        </el-form-item>
        <el-form-item label="库存"
                      prop="stock"
                      style="width:30%;">
          <el-input v-model="productForm.stock"
                    placeholder="请输入库存"
                    :disabled='isDisabled'></el-input>
        </el-form-item>
        <el-form-item label="产品料号图片"
                      prop="imageUrl"
                      style="width:50%">
          <el-upload class="avatar-uploader"
                     :show-file-list="false"
                     :multiple="false"
                     :before-upload="beforeUpload"
                     :http-request="httpRequest"
                     action
                     list-type="picture-card">
            <!-- 缩略图 -->
            <div v-if="updateForm.imageUrl"
                 style="height:100%">
              <el-image :src="updateForm.imageUrl"
                        fit="cover"
                        style="width: 100%; height: 100%"></el-image>
            </div>
            <i v-else
               class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="规格书"
                      prop="pdfUrl"
                      style="width:40%">
          <el-upload class="upload-demo"
                     drag
                     :show-file-list="false"
                     :multiple="false"
                     :before-upload="beforeUploadPdf"
                     :http-request="uploadPdf"
                     action>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip"
                 slot="tip">{{updateForm.pdfUrl}}</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="产品状态"
                      prop="isShow"
                      style="width:30%;">
          <el-radio v-model="productForm.isShow"
                    label="0"
                    :disabled='isDisabled'>未上架</el-radio>
          <el-radio v-model="productForm.isShow"
                    label="1"
                    :disabled='isDisabled'>上架</el-radio>
        </el-form-item>
        <el-form-item v-show="!isDisabled"
                      style="width:100%;">
          <el-button type="primary"
                     @click="dialogVisible2=true"
                     :disabled='isDisabled'>新增属性</el-button>
        </el-form-item>
        <el-form-item v-show="!isDisabled"
                      style="width:100%;">
          <el-button size="large"
                     type="primary"
                     style="width:22%"
                     @click="addInfo"
                     :disabled='isDisabled'>提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog title="新增属性"
               :visible.sync="dialogVisible2"
               width="30%"
               :before-close="handleClose">
      <el-form :model="productForm"
               label-position="right"
               label-width="100px"
               style="width:100%">
        <div v-for="(item,index) in newAttrData"
             :key="index"
             class="attrs">
          <el-form-item label="属性名">
            <el-input v-model="item.labelName"
                      placeholder="请输入属性名"
                      style="width:80%"></el-input>
          </el-form-item>
          <el-form-item label="属性值">
            <el-input v-model="item.attrName"
                      placeholder="请输入属性值"
                      style="width:80%"></el-input>
          </el-form-item>
          <i class="el-icon-circle-plus addAttr"
             @click="addAttr"></i>
        </div>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary"
                   @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  LIAOHAO_ADD, LIAOHAO_UPDATE,
  PRODUCT_IMAGE_FILE, PRODUCT_PDF_FILE, PRODUCT_LIST, UPDATE_PDF
} from "@/utils/api";
import axios from 'axios'
export default {
  data () {
    return {
      productCode: "",
      title: '新增料号',
      id: 0,
      liaohaoId: 0,
      modify: 0,
      productForm: {
        // id:0,
        // productNo: "",
        // produceName: "",
        // price: "",
        // stock: "",
        // isShow: "0"
      },
      // 上传
      updateForm: { imageUrl: '', pdfUrl: '' },
      file: null,
      loadings: '',
      hiddenFile: null,
      pdfFile: null,
      formRule: {},
      isDisabled: false,
      dialogImageUrl: "",
      dialogVisible1: false,
      dialogVisible2: false,
      newAttrData: [{ labelName: "型号", attrName: "T1000" }],
      newAttrForm: {},
      topDisabled: true,
      searchList: []
    };
  },
  mounted () {
    this.modify = 0
    console.log('+=2222==>' + this.$route.query["data"])
    console.log(this.$route.query)
    if (this.$route.query["data"]) {
      var ds = this.$route.query["handler"];
      this.productForm = this.$route.query['data']
      this.updateForm.imageUrl = this.productForm.image
      this.updateForm.pdfUrl = this.productForm.pdfUrl
      // console.log('+===>'+this.productForm.productCode)
      this.modify = 1
      this.isDisabled = ds == "check"
      this.topDisabled = true
      if (ds == "check") {
        this.title = '料号详情'
      } else {
        this.id = this.$route.query["pid"]
        this.liaohaoId = this.productForm.id
        this.title = '修改料号'
      }
      this.productCode = this.productForm.productCode
    } else
      if (this.$route.query["pid"]) {
        this.id = this.$route.query["pid"]
        this.isDisabled = this.$route.query["handler"] == "check" ? true : false;
        this.topDisabled = false
        this.modify = 0
        this.productForm = this.$route.query['product']
        this.title = '添加料号'
      }
  },
  methods: {
    querySearchAsync (queryString, cb) {
      PRODUCT_LIST({
        storeName: this.productCode,
        pageNo: 1,
        pageSize: 100
      }).then(res => {
        this.searchList = res.data.dataList
        var searchList = this.searchList
        for (let i = 0; i < searchList.length; i += 1) {
          searchList[i].value = searchList[i].productCode;
        }
        console.log(searchList)
        var results = queryString ? searchList.filter(this.createStateFilter(queryString)) : searchList;
        cb(results);
      })
    },
    createStateFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect (item) {
      console.log(item)
      this.id = item.id
    },
    // 上传前-拦截上传格式img
    beforeUpload (file) {
      console.log('==file==>' + file)
      this.updateForm.imageUrl = ''
      this.hiddenFile = file
    },
    httpRequest () {
      console.log('==httpRequest==>' + this.hiddenFile)
      // this.loadings = this.$pageLoading.service({
      //   lock: true,
      //   text: '正在上传中,请耐心等待',
      //   spinner: 'el-icon-loading'
      // })
      let param = new FormData()  // 创建form对象
      param.append('image', this.hiddenFile)
      let config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      var that = this
      axios.post('http://fox.foxcore.cn/api/v1/file/image/product', param, config)
        .then(response => {
          if (response.data.status === 200) {
            this.imageUrl = response.data.data
            this.updateForm.imageUrl = 'http://oss.dataos.top/' + response.data.data
            this.$message.success('上传图片成功')

          }
          console.log(response.data)
        })

    },
    // 上传前-拦截上传格式pdf
    beforeUploadPdf (file) {
      console.log('==file==>' + file)
      this.updateForm.pdfUrl = ''
      this.pdfFile = file
    },
    uploadPdf () {
      let param = new FormData()  // 创建form对象
      param.append('file', this.pdfFile)
      let config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      axios.post('http://fox.foxcore.cn/api/v1/file/pdf/product', param, config)
        .then(response => {
          if (response.data.status === 200) {
            this.pdfUrl = response.data.data
            this.updateForm.pdfUrl = 'http://oss.dataos.top/' + response.data.data
            this.$message.success('上传文档成功')
          }
        })
    },
    addInfo () {
      console.log('==this.modify==>' + this.modify)
      if (this.modify == 1) {
        this.updateLiaohao()
        this.upadtepdf()
        if (this.updateForm.pdfUrl != '') {
          this.upadtepdf()
        }
      } else {
        this.addLiaohao()
        if (this.updateForm.pdfUrl != '') {
          this.upadtepdf()
        }
      }
    },
    upadtepdf () {
      UPDATE_PDF({
        id: this.id,
        specsBook: this.updateForm.pdfUrl
      }).then(res => {
        console.log(res)
      })
    },
    addLiaohao () {
      var proCode;
      if (this.productCode == '') {
        proCode = this.productForm.productCode
      } else {
        proCode = this.productCode
      }
      LIAOHAO_ADD({
        productId: this.id,
        stock: this.productForm.stock,
        sales: 0,
        price: this.productForm.price,
        costPrice: this.productForm.costPrice,
        image: this.updateForm.imageUrl,
        isShow: this.productForm.isShow,
        productNumber: this.productForm.productNumber,
        productStoreName: this.productForm.productStoreName,
        attrName: this.productForm.attrName,
        attrVal: this.productForm.attrVal,
        productCode: proCode,
      }).then(res => {
        this.$message.success('操作成功')
        this.$router.push({
          path: "liaohao",
          query: {
            id: this.id
          }
        });
      });
    },
    updateLiaohao () {
      LIAOHAO_UPDATE({
        id: this.liaohaoId,
        productId: this.id,
        stock: this.productForm.stock,
        sales: 0,
        price: this.productForm.price,
        costPrice: this.productForm.costPrice,
        image: this.productForm.imageUrl,
        isShow: this.productForm.isShow,
        productNumber: this.productForm.productNumber,
        productStoreName: this.productForm.productStoreName,
        attrName: this.productForm.attrName,
        attrVal: this.productForm.attrVal,
        productCode: this.productForm.productCode,
      }).then(res => {
        this.$message.success('操作成功')
        this.$router.push({
          path: "liaohao",
          query: {
            id: this.id
          }
        });
      });
    },
    addAttr () {
      var obj = {
        labelName: "",
        attrName: ""
      };
      this.newAttrData.push(obj);
    },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
    },
    handleConfirm () {
      this.dialogVisible2 = false;
    },
    handleClose (done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.dialogVisible2 = false;
        })
        .catch(_ => { });
    }
  }
};
</script>

<style lang="scss" scoped>
.attrs {
  position: relative;
  .addAttr {
    font-size: 25px;
    color: rgb(64, 158, 255);
    margin-left: 15px;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 35px;
  }
}
</style>